package cn.tedu.icop.order.rabbit;

import cn.tedu.icop.order.config.RabbitConfiguration;
import cn.tedu.icop.order.pojo.po.OrderMQPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class RabbitMQOrderProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendOrder(OrderMQPO orderMQPO){
        log.debug("准备发送消息:{}",orderMQPO);
        //设置RabbitMQ return的回调类 并回执
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setReturnsCallback(returnedMessage -> {
            //returnedMessage 包含被退掉的信息,消息本身,错误码,错误的消息,
            //退订发生哪个交换机 ,发生在哪个路由key
            log.debug("returnMessage:{}",returnedMessage);
        });

        //设置RabbitMQ的确认confirm 机制的回调类 保证生成者消息不丢
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            log.debug("RabbitMQ确认回调:correlationData:{},ack:{},cause:{}",
                    correlationData,ack,cause);
            if (ack) {
                log.debug("RabbitMQ成功收到了消息");
            }else {
                log.debug("RabbitMQ没有收到了消息,打日志,进行重试,重新发送");
            }
        });
        //向延迟队列发消息
        rabbitTemplate.convertAndSend(RabbitConfiguration.EXCHANGE_NAME,
                RabbitConfiguration.ROUTING_KEY,orderMQPO);
    }
}

